package com.sptpc.stu.common.exception.handler;

import com.sptpc.stu.common.exception.BaseException;
import com.sptpc.stu.common.exception.BusinessException;
import com.sptpc.stu.common.response.JSONResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * GlobalExceptionHandler
 * Description: 统一的错误处理
 * @author alexchen
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

//    @ExceptionHandler(value = Exception.class)
//    @ResponseBody
//    public JSONResponse exception(Exception e) {
//        if (e instanceof NoHandlerFoundException) {
//            log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
//            return JSONResponse.ofStatus(Status.REQUEST_NOT_FOUND);
//        } else if (e instanceof HttpRequestMethodNotSupportedException) {
//            log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
//            return JSONResponse.ofStatus(Status.HTTP_BAD_METHOD);
//        } else if (e instanceof MethodArgumentNotValidException) {
//            log.error("【全局异常拦截】MethodArgumentNotValidException", e);
//            return JSONResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
//                    .getAllErrors()
//                    .get(0)
//                    .getDefaultMessage(), null);
//        } else if (e instanceof MethodArgumentTypeMismatchException) {
//            log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
//            return JSONResponse.ofStatus(Status.PARAM_NOT_MATCH);
//        } else if (e instanceof HttpMessageNotReadableException) {
//            log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
//            return JSONResponse.ofStatus(Status.PARAM_NOT_NULL);
//        }
//
//        log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
//        return JSONResponse.ofStatus(Status.ERROR);
//    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public JSONResponse businessExceptionHandle(BusinessException e) {
        log.error("【业务异常拦截】BusinessException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return JSONResponse.ofError(e);
    }
}
